package com.homework.fourth;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author WaveHi
 * @Date 24/8/2021 下午 7:50
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description 拓展题 ： 解析Mybatis.xml文件
 */
public class ReaderMyBaitsXML {

    public static void main(String[] args) {

        //获取配置文件
        File file = new File("day13/resources/mybatis.xml");

        //获取Document构建器工厂
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        Document document = null;

        try {

            //获取Document构建器
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            //通过Document构建器解析配置文件获取Document对象
            document = documentBuilder.parse(file);

        } catch (ParserConfigurationException e) {

            e.printStackTrace();

        } catch (SAXException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        //获取容器来接收数据
        HashMap<String, String> ssh = new HashMap<>();

        //获取根节点
        Element documentElement = document.getDocumentElement();

        //获取获取environment节点
        Element environments = (Element)documentElement.getElementsByTagName("environments").item(0);

        //获取environment节点
        Element environment = (Element)environments.getElementsByTagName("environment").item(0);

        //获取dataSource节点
        Element dataSource = (Element)environment.getElementsByTagName("dataSource").item(0);

        //获取property标记集
        NodeList properties = dataSource.getElementsByTagName("property");

        //获取property的数据
        for(int i = 0;i < properties.getLength();i++) {

            Element property = (Element)properties.item(i);
            ssh.put(property.getAttribute("name"),property.getAttribute("value"));

        }

        //输出容器的信息
        Set<Map.Entry<String, String>> entries = ssh.entrySet();
        for(Map.Entry<String,String> entry : entries) {

            System.out.println("name = " + entry.getKey() + ",value = " + entry.getValue());

        }

    }

}

//小结：Document对象的方法 Element getDocumentElement() 获取根节点
//     Element对象的方法 NodeList getElementsByTagName(String name) 获取由该节点指定标签名对应的后代标签组成的标签集
//                     String getAttribute(String property) 获取该节点指定属性的值
//     NodeList对象的方法 int getLength() 获取标签集的数据个数
//                      Node item(int index) 获取标签集指定位置的节点